<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :http-request="httpRequest"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <div class="content">
      <p>
        <span>文章标题</span>
        <el-input v-model="title" placeholder="文章标题"></el-input>
      </p>
      <p>
        <span>文章简介</span>
        <el-input v-model="summary" placeholder="文章简介"></el-input>
      </p>
      <p>
        <span>文章内容</span>
        <el-input v-model="content" placeholder="文章内容"></el-input>
      </p>
      <p>
        <el-button type="primary" @click="onSubmit" class="submitButton">提交</el-button>
      </p>
    </div>

    <div>
      <el-button type="primary" @click="text"></el-button>
      <img :src="text2"/>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      title: '',
      summary: '',
      content: '',
      imageUrl: '',
      text2: ''
    }
  },
  methods: {
    // 上传之前的格式设置
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest (data) {
      let rd = new FileReader() // 创建文件读取对象
      let file = data.file
      rd.readAsDataURL(file) // 文件读取装换为base64类型
      rd.onload = (e) => {
        this.imageUrl = e.target.result
        this.axios.post('api/uploadArticleImg', {
          imgData: this.imageUrl
        }).then(
          this.$message({
            message: '提交成功！',
            type: 'success'
          })
        )
      }
    },
    onSubmit () {
    },
    text () {
      this.axios.get('api/text').then((res) => {
        this.text2 = res.data[0].img
      })
    }
  }
}
</script>
